<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2018/3/28
 * Time: 17:38
 */

namespace app\admin\logic;


use app\common\utils\Constant;
use app\common\utils\IDCardUtils;
use app\common\utils\WeChatUtils;
use think\Config;
use think\Db;
use think\Exception;
use PHPExcel_Cell;
use PHPExcel_IOFactory;
use app\common\utils\PHPExcelUtils;
class VillageLogic
{

    /**
     * @param $filename
     * @param $village_id
     * @param $admin_id
     * @param string $encode
     * @return array
     */
    public function import($filename,$village_id,$admin_id, $encode = 'utf-8')
    {
        if (empty($village_id)) {
            return array('status' => 2, 'msg' => '请选择小区');
        }
        $count = model('Village')->where(array('id' => $village_id))->count();
        if ($count == 0) {
            return array('status' => 2, 'msg' => '小区不存在');
        }
        if (empty($filename)) {
            return array('status' => 2, 'msg' => '请上传Excel文件');
        }
        ini_set("memory_limit", "255M");
        Db::startTrans();
        try {
            setlocale(LC_ALL, 'zh_CN');
            $objReader = PHPExcel_IOFactory::createReader('Excel5');//读取xls
            if (!$objReader->canRead($filename)) {
                //读取xlsx
                $objReader = PHPExcel_IOFactory::createReader('Excel2007');
                if (!$objReader->canRead($filename)) {
                    return array('status' => 2, 'msg' => '无法读取文件');
                }
            }
            $objPHPExcel = $objReader->load($filename);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
            $highestColumn = $objWorksheet->getHighestColumn();
            $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
            $excelData = [];
            for ($row = 2; $row <= $highestRow; $row++) {
                $excelData[$row] = [];
                for ($col = 0; $col < $highestColumnIndex; $col++) {
                    $value = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                    if (!is_numeric($value) && $value != '') {
                        $value = mb_convert_encoding($value, 'utf-8');
                    }
                    $excelData[$row][] = $value;
                }
//                return array('status'=>0, 'msg'=>$excelData[$row]);
                $result = $this->checkData($excelData[$row], $row);
                if ($result['status'] == 0) {
                    Db::rollback();
                    $this->addImportLog($result['msg'], Constant::IMPORT_STATUS_FAILURE, $admin_id, $village_id);
                    return $result;
                }
             /*   if ($row % 1000 == 0) {
                    $result = $this->executeImport($excelData, $village_id, $admin_id);
                    if ($result['status'] == 0) {
                        return $result;
                    }
                }*/
            }
            if (count($excelData) > 0) {
                $result = $this->executeImport($excelData, $village_id, $admin_id);
                if ($result['status'] == 0) {
                    return $result;
                }
            }
            else{
                return array('status'=>0, 'msg'=>'文件为空');
            }
            Db::commit();
            //导入成功
            $remark = '导入成功';
            $status = Constant::IMPORT_STATUS_SUCCESS;
            $this->addImportLog($remark, $status, $admin_id, $village_id);//添加导入记录
            return array('status' => 1);
        } catch (\Exception $e) {
            Db::rollback();
            $remark = '服务器错误，'.$e->getMessage();
            $status = Constant::IMPORT_STATUS_FAILURE;
            $this->addImportLog($remark,$status,$admin_id,$village_id);//添加导入记录
            return array('status'=>0,'msg'=>'服务器错误，'.$e->getMessage());
        }
    }



    private function checkData($row_value,$current_row){
        $msg = '';
        $result = array('status'=>1,'msg'=>'');
        if(count($row_value) != 5){
            $result['status'] = 0;
            $result['msg'] = "导入第{$current_row}行数据失败，该行数据不完整";
            return $result;
        }
        $this->checkNull($row_value,$msg,$result);
        if($result['status'] == 0){
            $result['msg'] = "导入第{$current_row}行数据失败，".$msg;
            return $result;
        }
        if(!is_numeric($row_value['3'])){//未缴水费
            $result['status'] = 0;
            $msg.= ' 未缴水费必须为数字';
        }
        if($row_value['3'] < 0){//未缴水费
            $result['status'] = 0;
            $msg.= ' 未缴水费必须大于零';
        }
        if(!is_numeric($row_value['4'])){//未缴物业费
            $result['status'] = 0;
            $msg.= ' 未缴物业费必须为数字';
        }
        if($row_value['4'] < 0){//未缴物业费
            $result['status'] = 0;
            $msg.= ' 未缴物业费必须大于零';
        }
        $utils = new IDCardUtils();
        if(!$utils->validation_filter_id_card($row_value[1])){
            $result['status'] = 0;
            $msg.= ' 身份证格式不正确'.$row_value[1];
        }
       /* if(!is_mobile($row_value[2])){
            $result['status'] = 0;
            $msg.= ' 手机格式不正确';
        }*/
        if($result['status'] == 0){
            $result['msg'] = "导入第{$current_row}行数据失败，".$msg;
        }
        return $result;
    }

    private function checkNull($row_value,&$msg,&$result){
        if($row_value[0] == ''){
            $result['status'] = 0;
            $msg.= ' 业主名不能为空';
        }
        if($row_value[1] == ''){//身份证
            $result['status'] = 0;
            $msg.= ' 身份证不能为空';
        }
        if($row_value[2] == ''){//详细地址
            $result['status'] = 0;
            $msg.= ' 详细地址不能为空';
        }
        if($row_value[3] == ''){//未缴水费
            $result['status'] = 0;
            $msg.= ' 未缴水费不能为空';
        }
        if($row_value[4] == ''){//未缴物业费
            $result['status'] = 0;
            $msg.= ' 未缴物业费不能为空';
        }
    }


    /**
     * 添加导入记录
     * @param $remark string 备注
     * @param $status int 成功或失败
     * @param $admin_id int 管理员id
     * @param $village_id int
     */
    private function addImportLog($remark,$status,$admin_id,$village_id){
        $log['create_time'] = time();
        $log['remark'] = $remark;
        $log['type'] = Constant::IMPORT_TYPE_PAYMENT;
        $log['status'] = $status;
        $log['admin_id'] = $admin_id;
        $log['village_id'] = $village_id;
        return model('ImportLog')->insertGetId($log);

    }


    /**
     * 执行导入
     * @param $excelData
     * @param $village_id
     * @param $admin_id
     * @return array
     */
    private function executeImport(&$excelData,$village_id,$admin_id){
        $result = $this->importData($excelData, $village_id, $admin_id);
        $excelData = null;
        $excelData = [];
        if($result['status'] == 0){
            Db::rollback();
            $this->addImportLog($result['msg'],Constant::IMPORT_STATUS_FAILURE,$admin_id,$village_id);
        }
        return $result;
    }



    /**
     * 导入数据
     * @param $excelData
     * @param $village_id
     * @return array
     */
    private function importData($excelData,$village_id,$admin_id){
        $current_row = 0;
        $housePropertyIds = [];
        try {
            foreach ($excelData as $key => $row) {
                $current_row = $key;
                $map['detail'] = $row[2];
                $map['village_id'] = $village_id;
                $houseProperty = model("HouseProperty")->where($map)->find();
                if(!$houseProperty){
                    return array('status'=>0,'msg'=>"导入第{$current_row}行数据失败，该房产不存在");
                }
                else if(!$houseProperty['user_id']){
                    return array('status'=>0,'msg'=>"导入第{$current_row}行数据失败，该房产未绑定用户");
                }
                else{
                    $housePropertyIds[] = $houseProperty['id'];
                    model("HouseProperty")->where($map)->setInc("water_charge", $row[3]);
                    model("HouseProperty")->where($map)->setInc("property_charge", $row[4]);
//                    $houseProperty = model("HouseProperty")->where($map)->find();
                    model("HouseProperty")->where($map)->setInc("charge_total", $row[3] + $row[4]);
                    //添加记录
                    model("import_pay_log")->insert([
                        'house_property_id'   =>   $houseProperty['id']
                        ,'water_charge'       =>   $row[3]
                        ,'property_charge'    =>   $row[4]
                        ,'admin_id'           =>  $admin_id
                        ,'create_time'        =>  time()
                    ]);
                }
            }
            MessageLogic::getInstance()->sendMessageByHousePropertyPay($housePropertyIds);
            return array('status'=>1);
        }catch (Exception $e){
            return array('status'=>0,'msg'=>"导入第{$current_row}行数据失败，请检查数据格式是否正确 ".$e->getMessage());
        }
    }


    /**
     * 发送推送信息
     * @param $villageId 小区ID
     * @param $message 发送内容
     */
    public function sendMessage($villageId, $message)
    {
//        $weChat = Config::get('WeChat');
//        $wechatUtils = new WeChatUtils($weChat['app_id'], $weChat['app_secret'], $weChat['token']);
        $wechatUtils = WeChatUtils::getInstance();
        $userIds = model('HouseProperty')->where(array('village_id'=>$villageId))->field('user_id')->group("user_id")->select();
//        return $userIds;
        foreach ($userIds as $key => $value){
            //获取openid
            $openId = model('User')->where(array('id'=>$value['user_id']))->value('openid');
            if(!empty($openId) && $openId != ''){
                $wechatUtils->sendCustomerMessage($openId, $message);
                sleep(0.01);
            }
        }
    }


}